﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Eieboom.Models;
using System.Web.Mvc;
using System.Configuration;
using res = Sob.Resource.Models.Web.Web;
using System.Text.RegularExpressions;
using System.IO;
using Sob.Common;

namespace Eieboom.General
{
    public class WebUtils
    {
        /// <summary>
        /// 网站配置信息
        /// </summary>
        public static GeneralConfigInfo configinfo = GeneralConfigs.GetConfig();

        /// <summary>
        /// 分类链接url
        /// </summary>
        public static string GetCateUrl(CategoryModel category)
        {
            return GetCurrentLangPath()+ (!string.IsNullOrWhiteSpace(category.ReName) ? "/"+category.ReName + "/" : "/cate/" + category.CateId);
        }

        /// <summary>
        /// 文章链接url
        /// </summary>
        public static string GetArticleUrl(int id, string reName)
        {
            return !string.IsNullOrWhiteSpace(reName) ? "/article/" + reName : "/archive/" + id.ToString();
        }

        /// <summary>
        /// 文章链接url
        /// </summary>
        public static string GetArticleUrl(blog_varticle varticle)
        {
            return !string.IsNullOrWhiteSpace(varticle.rename) ? "/article/" + varticle.rename : "/archive/" + varticle.id.ToString();
        }

        /// <summary>
        /// 获得对应视图名称
        /// </summary>
        /// <param name="customView"></param>
        /// <param name="defaultView"></param>
        /// <returns></returns>
        public static string GetViewName(string customView,string defaultView)
        {
            return string.IsNullOrWhiteSpace(customView) ? defaultView : customView;
        }

        /// <summary>
        /// 获得配置文件路径
        /// </summary>
        /// <returns></returns>
        public static string GetWebConfigPath()
        {
            return ConfigurationManager.AppSettings["BlogConfig"].ToString();
        }

        /// <summary>
        /// 获得当前语言下分类语言文件名
        /// </summary>
        /// <returns></returns>
        public static string GetCategoryLangName()
        {
            string cateName = "Category.Lang.js";
            string weblang = Sob.Resource.Models.Web.Web.Lang != "" ? "." + Sob.Resource.Models.Web.Web.Lang : "";
            if (weblang != "")
                cateName = cateName.Replace(".js", weblang + ".js");
            return cateName;
        }

        /// <summary>
        /// 视图切换，记录session,cookie(用于缓存定制)以及更新视图引擎路径
        /// </summary>
        /// <param name="path"></param>
        public static void ChangeTheme(string key)
        {
            string theme=string.IsNullOrEmpty(key) ? "" : key;
            HttpContext.Current.Session["ThemeName"] = theme;

            HttpCookie themeCookie = new HttpCookie("web");
            themeCookie["theme"] = theme;
            themeCookie.Expires = DateTime.Now.AddDays(7d);
            HttpContext.Current.Response.Cookies.Add(themeCookie);

            DataCache.SetCache("DecorateCount", CurrentDecorateCount(), DateTime.Now.AddMinutes(180.0), TimeSpan.Zero);
             
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new BlogViewEngine(theme));
        }

        /// <summary>
        /// 当前语言路径
        /// </summary>
        public static string GetCurrentLangPath()
        {
            string currentlang = string.IsNullOrWhiteSpace(res.Lang) ? "zh-cn" : res.Lang;
            return currentlang != configinfo.DefaultLang ? "/" + currentlang : "";
        }

        /// <summary>
        /// 当前风格
        /// </summary>
        public static string GetCurrentTheme()
        {
            try
            {
                if (HttpContext.Current.Session["ThemeName"] != null)
                {
                    return HttpContext.Current.Session["ThemeName"].ToString();
                }
            }
            catch {
                ChangeTheme(Eieboom.General.WebUtils.configinfo.Theme);
            }
            return Eieboom.General.WebUtils.configinfo.Theme;
        }

        /// <summary>
        /// 获得页面类型下拉列表
        /// </summary>
        public static List<PageType> GetTypeList()
        {
            List<PageType> items = new List<PageType>();
            items.Add(new PageType
            {
                TypeName = Sob.Resource.Views.Admin.Admin.Article,
                TypeId = 1
            });
            items.Add(new PageType
            {
                TypeName = Sob.Resource.Views.Admin.Admin.SinglePage,
                TypeId = 2
            });
            items.Add(new PageType
            {
                TypeName = Sob.Resource.Views.Admin.Admin.Contributors,
                TypeId = 3
            });
            items.Add(new PageType
            {
                TypeName = Sob.Resource.Views.Admin.Admin.Album,
                TypeId = 4
            });
            //items.Add(new PageType
            //{
            //    TypeName = "论坛",
            //    TypeId = 5
            //});
            items.Add(new PageType
            {
                TypeName = Sob.Resource.Views.Admin.Admin.Message,
                TypeId = 6
            });
            items.Add(new PageType
            {
                TypeName = Sob.Resource.Views.Admin.Admin.CustomArea,
                TypeId = 7
            });
            items.Add(new PageType
            {
                TypeName = Sob.Resource.Views.Admin.Admin.CustomGlobalArea,
                TypeId = 8
            });
            return items;
        }

        /// <summary>
        /// 获得站点语言下拉列表
        /// </summary>
        public static List<PageLang> GetLangList()
        {
            List<PageLang> items = new List<PageLang>();
            items.Add(new PageLang
            {
                Key="中(简体)",
                Value = "zh-cn"
            });
            items.Add(new PageLang
            {
                Key = "中(繁体)",
                Value = "zh-tw"
            });
            items.Add(new PageLang
            {
                Key = "English",
                Value = "en-us"
            });
            return items;
        }

        public static readonly string[] Langs = new[] { "/en-us", "/zh-tw", "/zh-cn" };

        /// <summary>
        /// ubb转html
        /// </summary>
        /// <param name="argString"></param>
        /// <returns></returns>
        public static string ubb2html(string argString)
        {
            string tString = argString;
            if (tString != "")
            {
                Regex tRegex;
                bool tState = true;
                tString = tString.Replace("&", "&amp;");
                tString = tString.Replace(">", "&gt;");
                tString = tString.Replace("<", "&lt;");
                tString = tString.Replace("\"", "&quot;");
                tString = tString.Replace("&amp;#91;", "&#91;");
                tString = tString.Replace("&amp;#93;", "&#93;");
                tString = Regex.Replace(tString, @"\[br\]", "<br />", RegexOptions.IgnoreCase);
                string[,] tRegexAry = {
          {@"\[p\]([^\[]*?)\[\/p\]", "$1<br />"},
          {@"\[b\]([^\[]*?)\[\/b\]", "<b>$1</b>"},
          {@"\[i\]([^\[]*?)\[\/i\]", "<i>$1</i>"},
          {@"\[u\]([^\[]*?)\[\/u\]", "<u>$1</u>"},
          {@"\[ol\]([^\[]*?)\[\/ol\]", "<ol>$1</ol>"},
          {@"\[ul\]([^\[]*?)\[\/ul\]", "<ul>$1</ul>"},
          {@"\[li\]([^\[]*?)\[\/li\]", "<li>$1</li>"},
          {@"\[code\]([^\[]*?)\[\/code\]", "<div class=\"ubb_code\">$1</div>"},
          {@"\[quote\]([^\[]*?)\[\/quote\]", "<fieldset class=\"comment_quote\"><legend> "+Sob.Resource.Views.Home.Home.Quote+" </legend>$1</fieldset>"},
          //{@"\[quote\]([^\[]*?)\[\/quote\]", "<div class=\"ubb_quote\">$1</div>"},
          {@"\[color=([^\]]*)\]([^\[]*?)\[\/color\]", "<font style=\"color: $1\">$2</font>"},
          {@"\[hilitecolor=([^\]]*)\]([^\[]*?)\[\/hilitecolor\]", "<font style=\"background-color: $1\">$2</font>"},
          {@"\[align=([^\]]*)\]([^\[]*?)\[\/align\]", "<div style=\"text-align: $1\">$2</div>"},
          {@"\[url=([^\]]*)\]([^\[]*?)\[\/url\]", "<a href=\"$1\">$2</a>"},
          {@"\[img\]([^\[]*?)\[\/img\]", "<img src=\"$1\" />"}
        };
                while (tState)
                {
                    tState = false;
                    for (int ti = 0; ti < tRegexAry.GetLength(0); ti++)
                    {
                        tRegex = new Regex(tRegexAry[ti, 0], RegexOptions.IgnoreCase);
                        if (tRegex.Match(tString).Success)
                        {
                            tState = true;
                            tString = Regex.Replace(tString, tRegexAry[ti, 0], tRegexAry[ti, 1], RegexOptions.IgnoreCase);
                        }
                    }
                }
            }
            return tString;
        }

        /// <summary>
        /// 获得插图总数
        /// </summary>
        /// <returns></returns>
        public static int GetDecorateCount()
        {

            string cacheKey = "DecorateCount";
            object cache = DataCache.GetCache(cacheKey);
            if (cache == null)
            {
                try
                {
                    cache = CurrentDecorateCount();
                    if (cache != null)
                    {
                        DataCache.SetCache(cacheKey, cache, DateTime.Now.AddMinutes(180.0), TimeSpan.Zero);
                    }
                }
                catch (Exception) { }
            }
            return Utils.ObjectToInt(cache);
        }

        /// <summary>
        /// 当前风格下插图总数
        /// </summary>
        /// <returns></returns>
        private static int CurrentDecorateCount()
        {
            string decoratepath = GetCurrentTheme() == "" ? "/Content/image/decorate" : "/Themes/" + GetCurrentTheme() + "/Style/image/decorate";
            return Directory.GetFiles(System.Web.HttpContext.Current.Server.MapPath(decoratepath), "*.jpg").Length - 1;
        }

    }
}